package scholarsearch.activity;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import scholarsearch.android.R;




import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;

public class Carica extends Activity{
	private ImageView indietro;
	private List<String> item = null;
	private List<String> path = null;
	private static String rootScholar=Environment.getExternalStorageDirectory().toString()+"/scholarSearch";
	private static final int APRI_ID = Menu.FIRST;
	private static final int CANCELLA_ID = Menu.FIRST+1;
	private static final int ANNULLA_ID = Menu.FIRST+2;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.carica_ricerca_salvata); 
        File myNewFolder = new File(rootScholar);
        myNewFolder.mkdir();
        // STANZIAMENTO IMAGEVIEW
        indietro=(ImageView) findViewById(R.id.indietroCarica);
        indietro.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
			}
		});
        getDir(rootScholar);
    }
    
    private void getDir(String dirPath)
    {
    	
    	item = new ArrayList<String>();
    	path = new ArrayList<String>();
    	
    	File f = new File(dirPath);
    	File[] files = f.listFiles();
    	
    	for(int i=0; i < files.length; i++)
    	{
    			File file = files[i];
    			
    			if(file.isDirectory()==false){
    				if (file.getName().contains(".xml")){
    					path.add(file.getPath());
    					item.add(file.getName());
    				}
    			}
    				
    	}
    	
    	// STANZIAMENTO LISTVIEW
		ArrayList<HashMap<String, Object>> data=new ArrayList<HashMap<String,Object>>();
		
		
    	for (int i=0; i<item.size(); i++ ){
    		HashMap<String,Object> elementoMap=new HashMap<String, Object>();
    		elementoMap.put("elemento", item.get(i));
    		data.add(elementoMap);
    	}

    	
	    
	    String[] from={"elemento"}; //dai valori contenuti in queste chiavi
	    int[] to={R.id.elementoListView};//agli id dei layout
	    
	    //costruzione dell adapter
	    SimpleAdapter adapter=new SimpleAdapter(
	    		getApplicationContext(),
	    		data,//sorgente dati
	    		R.layout.elemento_listview_dati_opera, //layout contenente gli id di "to"
	    		from,
	    		to);
	   
	    //utilizzo dell'adapter
	    ListView listaRoot=(ListView)findViewById(R.id.listViewCarica);
	    listaRoot.setAdapter(adapter);
	    registerForContextMenu(findViewById(R.id.listViewCarica));
	    if (item.size()==0){
	        	new AlertDialog.Builder(this)
	    		.setTitle("Nessun file trovato!")
	    		.setPositiveButton("OK", 
	    				new DialogInterface.OnClickListener() {
	    					
	    					public void onClick(DialogInterface dialog, int which) {
	    						// TODO Auto-generated method stub
	    					}
	    				}).show();
	    }
    }
    
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
	   super.onCreateContextMenu(menu,v,menuInfo);
	   menu.setHeaderTitle("Opzioni"); 
	   menu.add(0,APRI_ID,0,"Apri");
	   menu.add(0,CANCELLA_ID,0,"Cancella");
	   menu.add(0,ANNULLA_ID,0,"Annulla");
	}
    
    @Override
	public boolean onContextItemSelected(MenuItem item) {
	   final AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
	   File file = new File(path.get(info.position));
		switch (item.getItemId()) {
		   case ANNULLA_ID:
		      return true;
		   case APRI_ID:
			   ArrayList<String> autori= new ArrayList<String>();
	   			autori.add("autore");
	   			Intent intent = new Intent(getApplicationContext(), RisultatiRicerca.class);
	   			String pkg=getPackageName();
	   			intent.putExtra(pkg+".carica", file.getName());
	   			intent.putStringArrayListExtra(pkg+".nomiAutori", autori);
	   			ArrayList<String> materie= new ArrayList<String>();
				materie.add("Tutte le materie");
	   			intent.putStringArrayListExtra(pkg+".materieRicerca", materie);
	   			intent.putExtra(pkg+".tipoRicerca", "Ricerca ovunque");
	            startActivity(intent);
	            finish();
			      return true;
		   case CANCELLA_ID:
			   Toast.makeText(Carica.this, "File "+file.getName()+" eliminato", Toast.LENGTH_LONG);
			   file.delete();
			   getDir(rootScholar);
		      return true;
		   default:
		      return super.onContextItemSelected(item);
		   }
		}
}
